package org.i9.slb.platform.anseko.provider.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.i9.slb.platform.anseko.common.BusinessException;
import org.i9.slb.platform.anseko.downstream.dto.param.FileCommandParamDto;
import org.i9.slb.platform.anseko.downstream.dto.result.CommandExecuteReDto;
import org.i9.slb.platform.anseko.provider.remote.CoreserviceRemoteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileWriter;

/**
 * file命令执行工具类
 *
 * @author R12
 * @date 2018.08.29
 */
public class FileCommandUtil {

    public static CommandExecuteReDto fileExecuteLocal(FileCommandParamDto fileCommandParamDto) throws Exception {
        logger.info("fileExecuteLocal 远程服务, param : {}, 开始", JSONObject.toJSONString(fileCommandParamDto));
        // 写入文件
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(new File(fileCommandParamDto.getFilePath()));
            fileWriter.write(fileCommandParamDto.getFileContent());
        } finally {
            if (fileWriter != null) {
                fileWriter.close();
            }
        }
        CommandExecuteReDto commandExecuteReDto = new CommandExecuteReDto();
        commandExecuteReDto.setCommandId(fileCommandParamDto.getCommandId());
        // 如果当前是否有命令
        if (StringUtils.isBlank(fileCommandParamDto.getCommandLine())) {
            commandExecuteReDto.setExecuteResult("success");
            return commandExecuteReDto;
        }
        try {
            ResultExcecution resultExcecution = ShellCommandUtil.shellExecuteLocal(fileCommandParamDto.getCommandLine());
            commandExecuteReDto.setExecuteResult(resultExcecution.getExecuteResult());
        } catch (BusinessException e) {
            logger.error("fileExecuteLocal 远程服务, param : {}, 异常", JSONObject.toJSONString(fileCommandParamDto), e);
            commandExecuteReDto.setExecuteResult(ExceptionUtils.exceptionToString(e));
            throw e;
        } catch (Exception e) {
            logger.info("fileExecuteLocal 远程服务, param : {}, 异常", JSONObject.toJSONString(fileCommandParamDto), e);
            commandExecuteReDto.setExecuteResult(ExceptionUtils.exceptionToString(e));
            throw e;
        } finally {
            CoreserviceRemoteService coreserviceRemoteService = SpringContextUtil.getBean(CoreserviceRemoteService.class);
            coreserviceRemoteService.remoteServiceCallbackCommandDispatch(commandExecuteReDto);
        }
        return commandExecuteReDto;
    }

    private static final Logger logger = LoggerFactory.getLogger(FileCommandUtil.class);
}
